﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using Code.BLL;
using Code.Models;
using Company.Web.Commen;
using Company.Web.Areas.Manage.Models.ProductModels;
using System.IO;
using System.Configuration;

namespace Company.Web.Areas.Manage.Controllers
{
    public class ProductController : ControllerBase
    {
        ProductManage PM = new ProductManage();

        #region 产品管理
        public ActionResult Index(IndexModel model)
        {
            if (model == null)
                model = new IndexModel();
            if (model.Serch == null)
                model.Serch = new IndexSerchModel();
            if (model.A < 1)
                model.A = null;
            if (model.B < 1)
                model.B = null;

            var page = model.A ?? 1;
            var size = model.B ?? 12;

            model.S = !(model.S ?? false);

            model.Parents = new List<ProductTypeItem>();
            model.Childs = new List<ProductTypeItem>();
            if (model.ID.HasValue)
            {
                var type = CommenManage.ProductTypes.FirstOrDefault(p => p.ID == model.ID);
                if (type != null)
                {
                    var parents = type.Parents.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                    model.Parents.AddRange(CommenManage.ProductTypes.Where(p => parents.Contains(p.ID)).OrderBy(p => p.Parents.Length)
                        .Select(p => new ProductTypeItem { ID = p.ID, Name_Ch = p.Name_Ch, Name_En = p.Name_En, ParentID = p.ParentID, Parents = p.Parents }));
                    model.Parents.Add(new ProductTypeItem { ID = type.ID, Name_Ch = type.Name_Ch, Name_En = type.Name_En, ParentID = type.ParentID, Parents = type.Parents });
                }
            }
            var pcount = PM.GetTable<Product>().Where(p => p.ProductType.Parents.Contains(model.ID + ",")).Select(p => new { p.ProductType.ID, p.ProductType.Parents }).ToArray();
            var childs = CommenManage.ProductTypes.Where(p => p.ParentID == model.ID || (p.ParentID == null && model.ID == null));
            model.Childs.AddRange(childs.Select(p => new ProductTypeItem
            {
                ID = p.ID,
                Name_Ch = p.Name_Ch,
                Name_En = p.Name_En,
                ParentID = p.ParentID,
                Parents = p.Parents,
                ProductCount = pcount.Where(p1 => p1.ID==p.ID || p1.Parents.Contains(p.ID + ",")).Count()
            }));

            model.Types = CommenManage.ProductTypes.ToArray();

            var products = PM.GetTable<Product>();
            if (model.S.HasValue && model.S.Value && model.ID.HasValue)
                products = products.Where(p => p.ProductType.ID == model.ID || p.ProductType.Parents.Contains("," + (model.ID ?? 0) + ","));
            else if (!model.S.Value)
                products = products.Where(p => p.ProductType.ID == model.ID);

            if (!string.IsNullOrEmpty(model.Serch.Number))
                products = products.Where(p => p.Identifier.Contains(model.Serch.Number) || p.ProductInfo_Ch.Name.Contains(model.Serch.Number) || p.ProductInfo_En.Name.Contains(model.Serch.Number));

            var defpic = CommenManage.ProductPictureTypes.FirstOrDefault(p => p.IsDefault);
            int def = defpic == null ? -1 : defpic.ID;
            model.SumCount=products.Count();
            //model.Products = products.OrderBy(p => p.ID).Skip(size * (page - 1)).Take(size)
            //    .Select(p => new ProductItem { ID = p.ID, Number = p.Identifier, Name_Ch = p.ProductInfo_Ch.Name, Name_En = p.ProductInfo_En.Name, DefaultPic = def != -1 ? (p.ProductPictures.Where(p1 => p1.IsDefault).Select(p1 => p1.FileName).FirstOrDefault() ?? p.ProductPictures.Where(p1 => p1.TypeID == def).Select(p1 => p1.FileName).FirstOrDefault() ?? p.ProductPictures.FirstOrDefault().FileName) : null, TypeID = p.TypeID, TypePath = p.ProductType.Parents })
            //    .ToArray().Each(p =>
            //    {
            //        var tmp = CommenManage.ProductTypes.Where(p1 => p1.ID == p.TypeID || p.TypePath.Contains("," + p1.ID + ",")).OrderBy(p1 => p1.Parents.Length);
            //        p.TypePath = string.Join("->", tmp.Select(p1 => p1.Name_Ch).ToArray());
            //    }).ToArray();

            model.Products = products.OrderBy(p => p.ID).Skip(size * (page - 1)).Take(size)
               .Select(p => new ProductItem
               {
                   ID = p.ID,
                   Number = p.Identifier,
                   Name_Ch = p.ProductInfo_Ch.Name,
                   Name_En = p.ProductInfo_En.Name,
                   DefaultPic = p.ProductPictures.OrderBy(pp => pp.IsDefault).Select(pp => pp.FileName).FirstOrDefault(),
                   TypeID = p.TypeID,
                   TypePath = p.ProductType.Parents
               })
               .ToArray().Each(p =>
               {
                   var tmp = CommenManage.ProductTypes.Where(p1 => p1.ID == p.TypeID || p.TypePath.Contains("," + p1.ID + ",")).OrderBy(p1 => p1.Parents.Length);
                   p.TypePath = string.Join("->", tmp.Select(p1 => p1.Name_Ch).ToArray());
               }).ToArray();

            return View(model);
        }

        public ActionResult Edit(long id)
        {
            var product = PM.GetTable<Product>().Select(p => new
            {
                p.ID,
                p.Identifier,
                p.TypeID,
                TypeName_Ch=p.ProductType.Name_Ch,
                TypeName_En=p.ProductType.Name_En,
                Name_Ch = p.ProductInfo_Ch.Name,
                Disc_Ch = p.ProductInfo_Ch.Discription,
                Name_En = p.ProductInfo_En.Name,
                Disc_En = p.ProductInfo_En.Discription,
                ClickCount = p.ClickCount,
            }).FirstOrDefault(p => p.ID == id);
            var pics = PM.GetTable<ProductPicture>().Where(p => p.ProductID == id);
            if (product == null)
                return RedirectToAction("index");
            var model = new ProductEditModel
            {
                ID = id,
                Action="edit",
                TypeID = product.TypeID,
                Number = product.Identifier,
                TypeName_Ch=product.TypeName_Ch,
                TypeName_En=product.TypeName_En,
                Name_Ch=product.Name_Ch,
                Name_En=product.Name_En,
                ClickCount=product.ClickCount,
                Disc_Ch = product.Disc_Ch.Split(new string[] { "\n&\r" }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(p =>
                    {
                        var t = p.Split(new string[] { "\n:\r" }, StringSplitOptions.None);
                        return new NameValueItem<string, string> { Key = t[0], Value = t[1] };
                    }).ToArray(),
                Disc_En = product.Disc_En.Split(new string[] { "\n&\r" }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(p =>
                    {
                        var t = p.Split(new string[] { "\n:\r" }, StringSplitOptions.None);
                        return new NameValueItem<string, string> { Key = t[0], Value = t[1] };
                    }).ToArray(),
            };
            model.Pictures = pics.Select(p => new PictureItem { ID = p.ID, FileName = p.FileName, IsDefault = p.IsDefault, TypeID = p.TypeID }).ToArray();
            model.PictureTypes = CommenManage.ProductPictureTypes.ToArray();
            model.Types = CommenManage.ProductTypes.ToArray();
            return View("Edit",model);
        }

        [HttpPost]
        public ActionResult Edit(ProductEditModel model)
        {
            model.PictureTypes = CommenManage.ProductPictureTypes.ToArray();

            if (model.Pictures != null && model.Pictures.Where(p => !(p.IsDel ?? false)).Count() == 0)
                ModelState.AddModelError("Pictures", "请至少上传一张产品图片");

            if (ModelState.IsValid)
            {

                var type = CommenManage.ProductTypes.FirstOrDefault(p => p.ID == model.TypeID);
                if (type == null)
                    return Content(Url.Action("index").Redirect("不存在该分类"));

                model.TypeName_Ch = type.Name_Ch;
                model.TypeName_En = type.Name_En;
                
                var path = ConfigurationManager.AppSettings["ImgUpLoadPath"] ?? "~/Content/Products/";
                if (!path.EndsWith("/"))
                    path += "/";

                var edit = "Edit".Equals(model.Action, StringComparison.CurrentCultureIgnoreCase);
                var r = new Random();
                model.Pictures.Where(p => p.IsNew ?? false).Each(p => p.FileName = string.Format("{3}{0:yyyy-MM}/{0:yyyyMMddHHmmss}{2}.{1}", DateTime.Now, p.FileName ?? "jpg", r.Next(1000, 9999), Url.Content(path)));
                var product = new Product
                {
                    Identifier = model.Number,
                    TypeID = model.TypeID.Value
                };
                var infos = new List<ProductInfo>();
                infos.Add(new ProductInfo_Ch { Name = model.Name_Ch, Discription = model.Disc_Ch == null || model.Disc_Ch.Length == 0 ? string.Empty : string.Join("\n&\r", model.Disc_Ch.Select(p => p.Key + "\n:\r" + p.Value).ToArray()) });
                infos.Add(new ProductInfo_En { Name = model.Name_En, Discription = model.Disc_En == null || model.Disc_En.Length == 0 ? string.Empty : string.Join("\n&\r", model.Disc_En.Select(p => p.Key + "\n:\r" + p.Value).ToArray()) });
                var dels = model.Pictures.Where(p => p.ID.HasValue && (p.IsDel ?? false)).Select(p => p.ID.Value);
                var ups = model.Pictures.Where(p => p.ID.HasValue && !(p.IsNew ?? false)).Select(p => new ProductPicture { FileName = p.FileName, IsDefault = p.IsDefault ?? false, TypeID = p.TypeID ,ID=p.ID.Value});
                var news = model.Pictures.Where(p => p.IsNew ?? false).Select(p => new ProductPicture { FileName = p.FileName, IsDefault = p.IsDefault ?? false, TypeID = p.TypeID });
                int rs = 0;

                if (edit)
                {
                    product.ID = model.ID.Value;
                    rs = PM.Edit(product, infos, ups, news, dels);
                }
                else
                {
                    rs = PM.Add(product, infos, news);
                }

                if (rs < 0)
                {
                    ViewData["msg"] = "操作失败，请稍后再试！".AlertOffPage();
                }
                else
                {
                    var dir=Server.MapPath(path+DateTime.Now.ToString("yyyy-MM"));
                    if(!Directory.Exists(dir))
                        Directory.CreateDirectory(dir);

                    model.Pictures.Each((p, i) =>
                        {
                            if (p.IsNew ?? false)
                            {
                                var sm = Request.Files["Pictures[" + i + "].File"].InputStream;
                                var f = System.IO.File.Create(Server.MapPath(p.FileName));
                                int l = 0;
                                var bf = new byte[2048];
                                while ((l = sm.Read(bf, 0, bf.Length)) > 0)
                                    f.Write(bf, 0, l);
                                f.Close();
                            }
                        });
                    if (edit)
                    {
                        model.Pictures.Where(p => p.ID.HasValue && (p.IsDel ?? false)).Each(p =>
                        {
                            try { System.IO.File.Delete(Server.MapPath(p.FileName)); }
                            catch { }
                        });
                    }
                    if (edit)
                        return Content(Url.Action(model.Action, new { id = model.ID }).Redirect("修改成功！"));
                    else
                        return Content(Url.Action(model.Action, new { id = model.TypeID }).Redirect("新增成功！"));
                }
            }
            if(model.Pictures!=null)
                model.Pictures = model.Pictures.Where(p => (p.IsNew ?? false) == false).ToArray();
            model.Types = CommenManage.ProductTypes.ToArray();
            return View("Edit",model);
        }

        public ActionResult Add(int? id)
        {
            var type = CommenManage.ProductTypes.FirstOrDefault(p => p.ID == id);
            var model = new ProductEditModel
            {
                Action="add",
                TypeID = id,
                Disc_Ch=new NameValueItem<string,string>[0],
                Disc_En=new NameValueItem<string,string>[0],
            };
            if (type != null)
            {
                model.TypeName_Ch = type.Name_Ch;
                model.TypeName_En = type.Name_En;
            }
            model.Pictures = new PictureItem[0];
            model.PictureTypes = CommenManage.ProductPictureTypes.ToArray();
            model.Types = CommenManage.ProductTypes.ToArray();
            return View("Edit",model);
        }

        [HttpPost]
        public ActionResult Add(ProductEditModel model)
        {
            return Edit(model);
        }

        public ActionResult Del(int? id,long a)
        {
            string msg=null;
            var product = PM.GetTable<Product>().FirstOrDefault();
            if (product == null)
                msg = "不存在该产品！";
            var pics = PM.GetTable<ProductPicture>().Where(p => p.ProductID == a).Select(p => p.FileName).ToArray();
            int rs = PM.Del(a);

            if (rs <= 0)
                msg = "删除失败？";
            else if (rs > 0)
            {
                pics.Each(p =>
                {
                    try { System.IO.File.Delete(Server.MapPath(p)); }
                    catch { }
                });
                msg = "删除成功！";
            }
            else
                msg = "系统错误，请稍后再试！";

            return Content(Url.Action("index", new { id }).Redirect(msg));

        }

        [ActionName("Index"), MultiButton("DelMore")]
        public ActionResult DelMore(long[] ChooseID, IndexModel model)
        {
            var pics = PM.GetTable<ProductPicture>().Where(p => ChooseID.Contains(p.ProductID)).Select(p => p.FileName);
            int rs = PM.Del(ChooseID);
            string msg;
            if (rs == 0)
                msg = "未进行更改";
            else if (rs > 0)
            {
                pics.Each(p =>
                {
                    try { System.IO.File.Delete(Server.MapPath(p)); }
                    catch { }
                });
                msg = "删除成功！";
            }
            else
                msg = "系统错误，请稍后再试！";
            ViewData["msg"] = msg.AlertOffPage();
            return Index(model);
        }

        #endregion

        #region 调整产品
        [ActionName("Index"), MultiButton("Move", Argument = "ChooseTypeID")]
        public ActionResult Move(int ChooseTypeID, long[] ChooseID, IndexModel model)
        {
            int rs = PM.MoveByID(ChooseTypeID, ChooseID);
            string msg;
            if (rs == 0)
                msg = "未进行更改";
            else if (rs > 0)
                msg = "操作成功！";
            else
                msg = "系统错误，请稍后再试！";
            ViewData["msg"] = msg.AlertOffPage();
            return Index(model);
        }
        #endregion

        #region  产品类型
        public ActionResult Type(ProductTypeModel model)
        {
            if (model == null)
                model = new ProductTypeModel();
            if (model.ProductType == null)
                model.ProductType = new ProductTypeEditModel { };
            model.ProductType.ParentID = model.ID;

            model.Parents = new List<ProductType>();
            model.Childs = new List<ProductType>();
            if (model.ID.HasValue)
            {
                var type = CommenManage.ProductTypes.FirstOrDefault(p => p.ID == model.ID);
                if (type != null)
                {
                    var parents = type.Parents.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                    model.Parents.AddRange(CommenManage.ProductTypes.Where(p => parents.Contains(p.ID)).OrderBy(p => p.Parents.Length));
                    model.Parents.Add(type);
                }
            }
            model.Childs.AddRange(CommenManage.ProductTypes.Where(p => p.ParentID == model.ID));

            return View(model);
        }

        [HttpPost]
        [ActionName("Type")]
        public ActionResult Type_New(ProductTypeModel model)
        {
            ProductType parent=null;
            if (model.ProductType.ParentID.HasValue)
            {
                parent = PM.GetTable<ProductType>().FirstOrDefault(p => p.ID == model.ProductType.ParentID);
                if (parent == null)
                {
                    ModelState.AddModelError("EditError", "不存在该上级分类");
                }
            }
            if (ModelState.IsValid)
            {
                var type = new ProductType
                {
                    Name_Ch = model.ProductType.Name_Ch,
                    Name_En = model.ProductType.Name_En,
                };
                if (parent != null)
                {
                    type.ParentID = parent.ID;
                    type.Parents = parent.Parents + parent.ID + ",";
                }
                int rs = PM.AddType(type);
                if (rs == 1)
                {
                    CommenManage.LoadProductType();
                    return Content(Url.Action("type", new { model.ID }).Redirect("新增分类成功！"));
                }
                else
                    ModelState.AddModelError("EditError", "添加失败，请稍后再试！");
            }
            return Type(model);
        }

        public ActionResult EditType(int id)
        {
            var type = PM.GetTable<ProductType>().FirstOrDefault(p => p.ID == id);
            if(type==null)
                return Content(Url.Action("type").Redirect("不存在该分类！"));
            var model = new ProductTypeEditModel
            {
                ID=id,
                ParentID=type.ParentID,
                Name_En=type.Name_En,
                Name_Ch=type.Name_Ch
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult EditType(ProductTypeEditModel model)
        {
            if(model.ID==null)
                return Content(Url.Action("type").Redirect("不存在该分类！"));
            if (ModelState.IsValid)
            {
                var type = new ProductType { ID = model.ID.Value, Name_Ch = model.Name_Ch, Name_En = model.Name_En };
                int rs = PM.EditType(type);
                if (rs == 1)
                {
                    CommenManage.LoadProductType();
                    return Content(Url.Action("type", new { id=model.ParentID }).Redirect("修改分类成功！"));
                }
                else
                    ModelState.AddModelError("EditError", "添加失败，请稍后再试！");
            }
            return View(model);
        }

        public ActionResult DelType(int? id,int a)
        {
            string msg=null;
            int rs = PM.DelType(a);
            if (rs == -2)
                msg = Url.Action("type", new { id = id }).Redirect("删除失败，该分类下有产品存在。？");
            else if (rs > 0)
            {
                CommenManage.LoadProductType();
                msg = Url.Action("type", new { id = id }).Redirect("删除成功！");
            }
            else
                msg = Url.Action("type", new { id = id }).Redirect("操作失败，请稍后再试！");
            return Content(msg);
        }
        #endregion

        #region 图片类型
        public ActionResult PicType()
        {
            var model = new PictureTypeModel();
            model.Types = PM.GetTable<ProductPictureType>().OrderBy(p => p.ID).ToArray();
            return View(model);
        }

        public ActionResult EditPicType(string id, int? a)
        {
            PictureTypeEditModel model = new PictureTypeEditModel { Model = id, IsDefault = false };
            if ("edit" == id)
            {
                var type = PM.GetTable<ProductPictureType>().FirstOrDefault(p => p.ID == a);
                if (type == null)
                    return Content(Url.Action("pictype").Redirect("不存在该分类！"));
                model.TypeID = a;
                model.IsDefault = type.IsDefault;
                model.Name_Ch = type.Name_Ch;
                model.Name_En = type.Name_En;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult EditPicType(PictureTypeEditModel model, string id)
        {
            if (ModelState.IsValid)
            {
                int rs = 0;
                var type = new ProductPictureType
                {
                    IsDefault = model.IsDefault ?? false,
                    Name_Ch = model.Name_Ch,
                    Name_En = model.Name_En,
                };
                if ("edit" == id)
                {
                    type.ID = model.TypeID.Value;
                    rs = PM.EditPicType(type);
                }
                else
                {
                    rs = PM.AddPicType(type);
                }
                string msg;
                if (rs > 0)
                {
                    CommenManage.LoadProductPictureType();
                    msg = ("edit" == id ? "修改" : "新增") + "成功！";
                }
                else
                    msg = "操作失败，请稍后再试！";
                return Content(Url.Action("pictype").Redirect(msg));
            }

            return View(model);

        }

        public ActionResult DelPicType(int id)
        { 
            string msg=null;
            int rs = PM.DelPicType(id);
            if (rs == -2)
                msg = "删除失败，该分类为默认分类\\r\\n请先设置别的分类为默认分类。？";
            else if (rs > 0)
            {
                CommenManage.LoadProductPictureType();
                msg = "删除成功！";
            }
            else
                msg = "系统错误，请稍后再试！";

            return Content(Url.Action("pictype").Redirect(msg));

        }
        #endregion
    }
}
